package com.xiaohu.sql

import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.{Column, DataFrame, SparkSession}

object Demo7Burks {
  def main(args: Array[String]): Unit = {
    val sparkSession: SparkSession = SparkSession.builder()
      .master("local")
      .appName("练习1需求")
      .config("spark.sql.shuffle.partitions", "1")
      .getOrCreate()

    import org.apache.spark.sql.functions._
    import sparkSession.implicits._

    val burksDF: DataFrame = sparkSession.read
      .format("csv")
      .schema("burk STRING,year STRING" +
        ",tsl01 DOUBLE,tsl02 DOUBLE,tsl03 DOUBLE" +
        ",tsl04 DOUBLE,tsl05 DOUBLE,tsl06 DOUBLE" +
        ",tsl07 DOUBLE,tsl08 DOUBLE,tsl09 DOUBLE" +
        ",tsl10 DOUBLE,tsl11 DOUBLE,tsl12 DOUBLE")
      .load("spark/data/burks.txt")

    /**
     * 1、统计每个公司每年按月累计收入  行转列 --> sum窗口函数
     *
     * 输出结果
     * 公司代码,年度,月份,当月收入,累计收入
     */
    // 纯sql的方式实现
    burksDF.createOrReplaceTempView("burks")
    val resDF1: DataFrame = sparkSession.sql(
      """
        |select
        |t1.burk as burk,
        |t1.year as year,
        |t1.month as month,
        |t1.tsl as tsl,
        |sum(t1.tsl) over(partition by burk,year order by month) as leiji
        |from
        |(select
        | burk,
        | year,
        | month,
        | tsl
        |from
        | burks
        | lateral view explode(map(1,tsl01,2,tsl02,3,tsl03,4,tsl04,5,tsl05,6,tsl06,7,tsl07,8,tsl08,9,tsl09,10,tsl10,11,tsl11,12,tsl12)) T as month,tsl
        | ) t1
        |""".stripMargin)

    val m: Column = map(
      expr("1"), $"tsl01",
      expr("2"), $"tsl02",
      expr("3"), $"tsl03",
      expr("4"), $"tsl04",
      expr("5"), $"tsl05",
      expr("6"), $"tsl06",
      expr("7"), $"tsl07",
      expr("8"), $"tsl08",
      expr("9"), $"tsl09",
      expr("10"), $"tsl10",
      expr("11"), $"tsl11",
      expr("12"), $"tsl12"
    )

    // DSL语法方式实现
//    burksDF.select($"burk",$"year",explode(m) as Array("month","tsl"))
//      .withColumn("leiji",sum($"tsl") over Window.partitionBy($"burk",$"year").orderBy($"month"))
//      .show()

    /**
     * 2、统计每个公司当月比上年同期增长率  行转列 --> lag窗口函数
     * 公司代码,年度,月度,增长率（当月收入/上年当月收入 - 1）
     *
     * 853101 2010 1 10000
     * 853101 2011 1 11000  10000
     */
    val resDF2: DataFrame = burksDF.select($"burk", $"year", explode(m) as Array("month", "tsl"))
      .withColumn("beforeTsl", lag($"tsl", 1, 0.0) over Window.partitionBy($"burk", $"month").orderBy($"year"))
      .withColumn("p", round(($"tsl" / $"beforeTsl" - 1) * 100, 8).cast("string"))
      .withColumn("new_p", when($"p".isNotNull, $"p").otherwise("该年的当月是第一次计数"))
      .select($"burk", $"year", $"month", $"tsl", $"new_p")



  }
}
